package com.iwe.crm.workbench.service.impl;

import com.iwe.crm.base.bean.ResultVo;
import com.iwe.crm.base.exception.CrmEnum;
import com.iwe.crm.base.exception.CrmException;
import com.iwe.crm.base.util.CommonUtil;
import com.iwe.crm.base.util.DateUtil;
import com.iwe.crm.user.bean.User;
import com.iwe.crm.workbench.bean.*;
import com.iwe.crm.workbench.mapper.*;
import com.iwe.crm.workbench.service.ClueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ClueServiceImpl implements ClueService {

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ClueActivityRelationMapper clueActivityRelationMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired
    private ContactsRemarkMapper contactsRemarkMapper;

    @Autowired
    private CustomerRemarkMapper customerRemarkMapper;

    @Autowired
    private ContactActivityRelationMapper contactActivityRelationMapper;

    @Autowired
    private TranMapper tranMapper;

    @Autowired
    private TranHistoryMapper tranHistoryMapper;

    @Autowired
    private TranRemarkMapper tranRemarkMapper;

    @Autowired
    private ClueRemarkMapper clueRemarkMapper;

    @Override
    public List<Activity> queryActivies(String name,String clueId) {
        //1、先查询出当前线索已经关联过的市场活动
        ClueActivityRelation clueActivityRelation = new ClueActivityRelation();
        clueActivityRelation.setClueId(clueId);
        List<ClueActivityRelation> clueActivityRelations =
                clueActivityRelationMapper.select(clueActivityRelation);

        List<String> clueIds = new ArrayList<>();
        for (ClueActivityRelation activityRelation : clueActivityRelations) {
            clueIds.add(activityRelation.getActivityId());
        }
        //2、模糊查询出市场活动,排除已经关联过的市场活动
        Example example = new Example(Activity.class);
        Example.Criteria criteria = example.createCriteria();
        if(clueIds.size() == 0){
            //说明当前线索未关联任何市场活动
            criteria.andLike("name","%" + name + "%");
        }else{
            criteria.andLike("name","%" + name + "%")
                    .andNotIn("id",clueIds);
        }
        List<Activity> activities = activityMapper.selectByExample(example);
        return activities;
    }

    @Override
    public void bind(String clueId, String aids) {
        String[] ids = aids.split(",");
        for (String activityId : ids) {
            ClueActivityRelation clueActivityRelation = new ClueActivityRelation();
            clueActivityRelation.setId(CommonUtil.uuid());
            clueActivityRelation.setClueId(clueId);
            clueActivityRelation.setActivityId(activityId);
            clueActivityRelationMapper.insertSelective(clueActivityRelation);
        }

    }

    @Override
    public List<Activity> updateRelation(String clueId) {
        ClueActivityRelation clueActivityRelation = new ClueActivityRelation();
        clueActivityRelation.setClueId(clueId);

        //根据线索主键查询中间表对象
        List<ClueActivityRelation> clueActivityRelations =
                clueActivityRelationMapper.select(clueActivityRelation);

        List<Activity> activities = new ArrayList<>();
        for (ClueActivityRelation activityRelation : clueActivityRelations) {
            //市场活动主键
            String activityId = activityRelation.getActivityId();
            //更具主键查询市场活动
            Activity activity = activityMapper.selectByPrimaryKey(activityId);

            activities.add(activity);
        }
        return activities;
    }

    @Override
    public void clueActivityRelation(ClueActivityRelation clueActivityRelation) {
        clueActivityRelationMapper.delete(clueActivityRelation);
    }

    @Override
    public Clue queryById(String id) {
        return clueMapper.selectByPrimaryKey(id);
    }

    @Override
    public void convert(String id, User user,String isCreateTransaction,Tran tran) {
        int count = 0;
        //1、根据主键查询线索数据
        Clue clue = clueMapper.selectByPrimaryKey(id);
        //2、先将线索中的客户信息取出来保存在客户表中，
        // 当该客户不存在的时候，新建客户(按公司名称精准查询)
        String company = clue.getCompany();
        Customer customer = new Customer();
        customer.setName(company);
        List<Customer> customers = customerMapper.select(customer);
        if(customers.size() == 0){
            //系统中没有客户存在
            customer.setAddress(clue.getAddress());
            customer.setId(CommonUtil.uuid());
            customer.setContactSummary(clue.getContactSummary());
            customer.setDescription(clue.getDescription());
            customer.setCreateTime(DateUtil.dateToString(new Date()));
            customer.setPhone(clue.getPhone());
            customer.setWebsite(clue.getWebsite());
            customer.setOwner(clue.getOwner());
            customer.setNextContactTime(clue.getNextContactTime());
            customer.setContactSummary(clue.getContactSummary());
            count = customerMapper.insertSelective(customer);
            if(count == 0){
                throw new CrmException(CrmEnum.CLUE_CONVERT);
            }
        }else {
            customer = customers.get(0);
        }
        //3、将线索中联系人信息取出来保存在联系人表中
        Contacts contacts = new Contacts();
        contacts.setId(CommonUtil.uuid());
        contacts.setOwner(clue.getOwner());
        contacts.setSource(clue.getSource());
        //客户主键
        contacts.setCustomerId(customer.getId());
        contacts.setFullname(clue.getFullname());
        contacts.setAppellation(clue.getAppellation());
        contacts.setEmail(clue.getEmail());
        contacts.setMphone(clue.getMphone());
        contacts.setJob(clue.getJob());
        contacts.setCreateBy(user.getName());
        contacts.setCreateTime(DateUtil.dateToString(new Date()));
        count = contactsMapper.insertSelective(contacts);
        if(count == 0){
            throw new CrmException(CrmEnum.CLUE_CONVERT);
        }
        //4、线索中的备注信息取出来保存在客户备注和联系人备注中
        //4.1 先保存客户备注
        CustomerRemark customerRemark = new CustomerRemark();
        customerRemark.setId(CommonUtil.uuid());
        customerRemark.setCreateBy(user.getName());
        customerRemark.setCreateTime(DateUtil.dateToString(new Date()));
        customerRemark.setCustomerId(clue.getId());

        customerRemarkMapper.insertSelective(customerRemark);
        //4.2 再保存联系人备注
        ContactsRemark contactsRemark = new ContactsRemark();
        contactsRemark.setId(CommonUtil.uuid());
        contactsRemark.setCreateBy(user.getName());
        contactsRemark.setCreateTime(DateUtil.dateToString(new Date()));
        contactsRemark.setContactsId(contacts.getId());

        contactsRemarkMapper.insertSelective(contactsRemark);


        //5、将"线索和市场活动的关系"转换到"联系人和市场活动的关系中"
        //5.1、将线索和市场活动的关联表中市场活动主键取出来
        ClueActivityRelation clueActivityRelation = new ClueActivityRelation();
        clueActivityRelation.setClueId(id);
        List<ClueActivityRelation> clueActivityRelations =
                clueActivityRelationMapper.select(clueActivityRelation);

        //5.2、把新的联系人和市场活动关联数据插入到联系人和市场活动关联表中

        for (ClueActivityRelation activityRelation : clueActivityRelations) {
            ContactActivityRelation contactActivityRelation =
                    new ContactActivityRelation();
            contactActivityRelation.setId(CommonUtil.uuid());
            contactActivityRelation.setActivityId(activityRelation.getActivityId());
            contactActivityRelation.setContactsId(contacts.getId());
            contactActivityRelationMapper.insertSelective(contactActivityRelation);
        }
        //6、如果转换过程中发生了交易，创建一条新的交易，
        // 交易信息不全，后面可以通过修改交易来完善交易信息
        if("1".equals(isCreateTransaction)){
            //发生交易了
            tran.setId(CommonUtil.uuid());
            tran.setCreateBy(user.getName());
            tran.setCreateTime(DateUtil.dateToString(new Date()));

            tranMapper.insertSelective(tran);

            //7、创建该条交易对应的交易历史以及备注
            //7.1创建交易历史
            TranHistory tranHistory = new TranHistory();
            tranHistory.setCreateBy(user.getName());
            tranHistory.setTranId(tran.getId());
            tranHistory.setId(CommonUtil.uuid());
            tranHistory.setMoney(tran.getMoney());
            tranHistory.setExpectedDate(tran.getExpectedDate());
            tranHistory.setStage(tran.getStage());
            tranHistory.setCreateTime(DateUtil.dateToString(new Date()));
            tranHistoryMapper.insertSelective(tranHistory);
            //7.2创建交易备注
            TranRemark tranRemark = new TranRemark();
            tranRemark.setId(CommonUtil.uuid());
            tranRemark.setCreateBy(user.getName());
            tranRemark.setCreateTime(DateUtil.dateToString(new Date()));
            tranRemark.setTranId(tran.getId());

            tranRemarkMapper.insertSelective(tranRemark);
        }


        //8、删除线索的备注信息
        ClueRemark clueRemark = new ClueRemark();
        clueRemark.setClueId(id);
        clueRemarkMapper.delete(clueRemark);

        //9、删除线索和市场活动的关联关系
        ClueActivityRelation clueActivityRelation1 = new ClueActivityRelation();
        clueActivityRelation1.setClueId(id);
        clueActivityRelationMapper.delete(clueActivityRelation1);

        //10、删除线索
        clueMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Activity> queryRelatedActivity(String id, String name) {
        //1、先查询线索和市场活动关联表，取出市场活动主键，放入到集合中
        List<String> aids = new ArrayList<>();
        ClueActivityRelation clueActivityRelation = new ClueActivityRelation();
        clueActivityRelation.setClueId(id);
        List<ClueActivityRelation> clueActivityRelations =
                clueActivityRelationMapper.select(clueActivityRelation);
        for (ClueActivityRelation activityRelation : clueActivityRelations) {
            aids.add(activityRelation.getActivityId());
        }

        //2、查询市场活动，让主键in aids范围
        Example example = new Example(Activity.class);
        Example.Criteria criteria = example.createCriteria();
        if(aids.size() == 0){
            //说明当前线索还没有关联过任何市场活动
            throw new CrmException(CrmEnum.CLUE_NOT_RELATION);
        }else{
            criteria. andLike("name","%" + name + "%")
                    .andIn("id",aids);
        }
        List<Activity> activities = activityMapper.selectByExample(example);
        return activities;
    }
}
